﻿package com.superwindcloud.blackjack

import android.media.MediaPlayer
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import kotlin.random.Random

@Composable
private fun playersStartAskingForCards(
    whetherToStartAskingForCards1: MutableState<Boolean>,
    cardResourceIds1: MutableList<Int>,
    PlayerCurrentScore: MutableState<Int>
) {
    val context = LocalContext.current
    Log.d("MainActivity", "DealingPlayerCard")
    if (whetherToStartAskingForCards1.value == true) {
        LaunchedEffect(whetherToStartAskingForCards1.value) {
            addNewCard(cardResourceIds1, PlayerCurrentScore, context)
            whetherToStartAskingForCards1.value = false
        }

    }
}

@Composable
fun playerBettingOperationInterface(
    rememberChipValue: MutableState<Int>,
    rememberRemainingChips: MutableState<Int>,
    isGameStarted: MutableState<Boolean>,
    dealerInitScore: MutableState<Int>,
    isDealerTurnToAskForCards: MutableState<Boolean>,
    PlayerCurrentScore: MutableState<Int>,
    theDealerHasFinishedTakingTheCards: MutableState<Boolean>,
) {
    val whetherToChooseToDouble = remember { mutableStateOf(false) }
    val whetherToSuspendTrading = remember { mutableStateOf(false) }
    val whetherToStartAskingForCards = remember { mutableStateOf(false) }
    val cardResourceIds = remember { mutableStateListOf<Int>() }


    val showGameOverDialogBobCard = remember { mutableStateOf(false) }
    val showGameOverBlackJackForPlayer = remember { mutableStateOf(false) }
    PlayerCard(PlayerCurrentScore, cardResourceIds ,  showGameOverDialogBobCard , rememberChipValue ,rememberRemainingChips)
    if (whetherToSuspendTrading.value == true) isDealerTurnToAskForCards.value = true
    if (isGameStarted.value == true && !showGameOverBlackJackForPlayer.value &&
        !showGameOverDialogBobCard.value && !isDealerTurnToAskForCards.value
    ) {
        PlayerInterface(
            PlayerCurrentScore,
            cardResourceIds,
            whetherToChooseToDouble,
            whetherToSuspendTrading,
            whetherToStartAskingForCards
        )
    }
    if (PlayerCurrentScore.value == 21) {
        Log.d("MainActivity", "21点赢了"); // 加倍后牌局结束
        showGameOverBlackJackForPlayer.value = true

    }
    if (whetherToChooseToDouble.value == true) {
        Log.d("MainActivity", "whetherToChooseToDouble.value = true"); // 加倍
        ApplyDoubleButton(rememberChipValue, whetherToChooseToDouble)
        addNewCard(cardResourceIds, PlayerCurrentScore, LocalContext.current)
        if (PlayerCurrentScore.value > 21) {
            showGameOverDialogBobCard.value = true
            Log.d("MainActivity", "爆牌输了"); // 加倍后牌局结束

        } else if (PlayerCurrentScore.value == 21) {
            Log.d("MainActivity", "21点赢了"); // 加倍后牌局结束
            showGameOverBlackJackForPlayer.value = true

        } else {
            isDealerTurnToAskForCards.value = true
        }

    }
    // 转到庄家回合结算
    val dealerCardResourceIds = remember { mutableListOf<Int>() }

    DealerAskForCards(
        rememberChipValue, rememberRemainingChips, isDealerTurnToAskForCards,
        dealerInitScore, dealerCardResourceIds, theDealerHasFinishedTakingTheCards
    )
    BobCard(rememberChipValue, rememberRemainingChips, showGameOverDialogBobCard)
    BlackJackForPlayer(rememberChipValue, rememberRemainingChips, showGameOverBlackJackForPlayer)
}

@Composable
fun PlayerInterface(
    PlayerCurrentScore: MutableState<Int>, cardResourceIds: MutableList<Int>,
    whetherToChooseToDouble: MutableState<Boolean>,
    whetherToSuspendTrading: MutableState<Boolean>,
    whetherToStartAskingForCards: MutableState<Boolean>
) {
    Box(modifier = Modifier.fillMaxSize()) {
        Log.d("MainActivity", "playerBettingOperationInterface")

        val doubleButtonIsClicked = remember { mutableStateOf(false) }
        //   要牌 , 停牌,加倍

        if (whetherToSuspendTrading.value == true) {
            doubleButtonIsClicked.value = true
        }
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .align(Alignment.Center)
                .offset(y = 100.dp)
                .padding(start = 20.dp, bottom = 30.dp),
            horizontalArrangement = Arrangement.spacedBy(20.dp, Alignment.CenterHorizontally), // 使图片均匀分布
            verticalAlignment = Alignment.CenterVertically // 设置垂直居中
        ) {
            Button(
                modifier = Modifier
                    .size(60.dp)
                    .clickable {
                        Log.d("MainActivity", "hit button clicked")
                    },
                contentPadding = PaddingValues(0.dp),
                shape = RoundedCornerShape(16.dp),
                content = {
                    Text(
                        text = "要牌",
                        fontSize = 15.sp, fontWeight = FontWeight.Bold,
                        fontStyle = FontStyle.Italic, color = Color.White
                    )
                },
                onClick = {
                    Log.d("MainActivity", "hit button clicked")
                    whetherToStartAskingForCards.value = true

                }
            )
            Button(
                modifier = Modifier
                    .size(60.dp)
                    .clickable {
                        Log.d("MainActivity", "stand button clicked")
                    },
                contentPadding = PaddingValues(0.dp),
                shape = RoundedCornerShape(16.dp),
                content = {
                    Text(
                        text = "停牌",
                        fontSize = 15.sp, fontWeight = FontWeight.Bold,
                        fontStyle = FontStyle.Italic, color = Color.White
                    )
                }, onClick = {
                    whetherToSuspendTrading.value = true
                    Log.d("MainActivity", "hit button clicked")
                }
            )
            Button(
                modifier = Modifier
                    .size(60.dp)
                    .clickable {
                        Log.d("MainActivity", "double button clicked")
                    },
                contentPadding = PaddingValues(0.dp),
                shape = RoundedCornerShape(16.dp),
                enabled = !doubleButtonIsClicked.value,
                content = {
                    Text(
                        text = "加倍",
                        fontSize = 15.sp, fontWeight = FontWeight.Bold,
                        fontStyle = FontStyle.Italic, color = Color.White
                    )
                }, onClick = {
                    Log.d("MainActivity", "hit button clicked")
                    whetherToChooseToDouble.value = true
                    doubleButtonIsClicked.value = true
                }
            )


        }

    }
    playersStartAskingForCards(whetherToStartAskingForCards, cardResourceIds, PlayerCurrentScore)
}

@Composable
fun BlackJackForPlayer(
    rememberChipValue: MutableState<Int>,
    rememberRemainingChips: MutableState<Int>,
    showGameOverBlackJackForPlayer: MutableState<Boolean>
) {

    val context = LocalContext.current
    if (showGameOverBlackJackForPlayer.value == true) {
        LaunchedEffect(showGameOverBlackJackForPlayer.value) {
            rememberRemainingChips.value += rememberChipValue.value * 2
        }
        Box(modifier = Modifier.fillMaxSize()) {
            Image(
                painter = painterResource(id = R.drawable.point_black_jack),
                contentDescription = "lose",
                modifier = Modifier
                    .size(200.dp)
                    .align(Alignment.Center)
                    .padding(top = 100.dp)
            )
        }
        LaunchedEffect(showGameOverBlackJackForPlayer.value) {
            val mediaPlayer = MediaPlayer.create(context, R.raw.sound_win)
            mediaPlayer.start()
            mediaPlayer.setOnCompletionListener {
                it.release() // 在音频播放完成后释放资源
            }
        }
    }
}

@Composable
fun BobCard(
    rememberChipValue: MutableState<Int>,
    rememberRemainingChips: MutableState<Int>,
    showGameOverDialogBobCard: MutableState<Boolean>
) {
    if (showGameOverDialogBobCard.value == true) {
        LaunchedEffect(showGameOverDialogBobCard.value) {
            rememberRemainingChips.value -= rememberChipValue.value
        }
        Box(modifier = Modifier.fillMaxSize()) {
            Image(
                painter = painterResource(id = R.drawable.point_user_bob_lose),
                contentDescription = "lose",
                modifier = Modifier
                    .size(200.dp)
                    .align(Alignment.Center)
                    .padding(top = 100.dp)
            )
        }
        val context = LocalContext.current
        LaunchedEffect(showGameOverDialogBobCard.value) {
            val mediaPlayer = MediaPlayer.create(context, R.raw.sound_cheer0)
            mediaPlayer.start()
            mediaPlayer.setOnCompletionListener {
                it.release() // 在音频播放完成后释放资源
            }
        }
    }
}

@Composable
fun GameOverDialog(
    showGameOverDialog: MutableState<Boolean>,
    isGameStarted: MutableState<Boolean>,
    PlayerCurrentScore: MutableState<Int>
) {
    if (showGameOverDialog.value)
        Dialog(
            onDismissRequest = {
                showGameOverDialog.value = false
            },
            properties = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)
        ) {
            Box(
                modifier = Modifier
                    .fillMaxSize()   // 自定义宽高
                    .padding(16.dp)
            ) {
                Column(
                    modifier = Modifier
                        .padding(0.dp)
                        .wrapContentSize(),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {
                    Image(
                        painter = painterResource(id = R.drawable.point_user_bob_lose),
                        contentDescription = "lose",
                        modifier = Modifier.size(150.dp) // 调整图片大小
                    )
                    Text(
                        text = "爆牌你输了，庄家赢了",
                        fontSize = 20.sp, fontWeight = FontWeight.Bold,
                        fontStyle = FontStyle.Italic, color = Color.Magenta
                    )
                }
            }
            Button(onClick = {
                Log.d("MainActivity", "重新开始游戏")
                showGameOverDialog.value = false
                isGameStarted.value = false;
                PlayerCurrentScore.value = 2000;
            }) {
                Text(text = "重新开始")
            }
        }
}

@Composable
fun ApplyDoubleButton(
    rememberChipValue: MutableState<Int>,
    whetherToChooseToDouble: MutableState<Boolean>
) {
    rememberChipValue.value *= 2;
    whetherToChooseToDouble.value = false;
}


private fun addNewCard(
    cardResourceIds: MutableList<Int>,
    playerCurrentScore: MutableState<Int>,
    context: android.content.Context
) {
    val baseCardScore = Random.nextInt(1, 14) // 1-13
    var result = playerCurrentScore.value

    // 根据新添加的卡片更新分数
    if (baseCardScore >= 11) {
        result += 10
    } else if (baseCardScore == 1) {
        if (result + 11 <= 21) {
            result += 11
        } else {
            result += 1
        }
    } else {
        result += baseCardScore
    }

    playerCurrentScore.value = result

    // 根据新添加的卡片确定资源 ID
    val randomColor = Random.nextInt(1, 5) // 1-4
    val cardStr = when (randomColor) {
        1 -> "card_clubs_$baseCardScore"
        2 -> "card_diamonds_$baseCardScore"
        3 -> "card_hearts_$baseCardScore"
        4 -> "card_spades_$baseCardScore"
        else -> ""
    }
    val resId = context.resources.getIdentifier(cardStr, "drawable", context.packageName)
    if (resId != 0) {
        cardResourceIds.add(resId)
    }
}

@Composable
fun PlayerCard(
    PlayerCurrentScore: MutableState<Int>,
    cardResourceIds: MutableList<Int>,
    showGameOverDialogBobCard: MutableState<Boolean>,
    rememberChipValue: MutableState<Int>,
    rememberRemainingChips: MutableState<Int>
) {

 if (PlayerCurrentScore.value  >21) {
     showGameOverDialogBobCard.value = true
     Log.d("MainActivity", "爆牌输了"); // 加倍后牌局结束
     LaunchedEffect(showGameOverDialogBobCard.value) {
         rememberRemainingChips.value -= rememberChipValue.value
     }
 }
    val context = LocalContext.current
    // 初始化两张卡片
    LaunchedEffect(Unit) {
        addNewCard(cardResourceIds, PlayerCurrentScore, context)
        addNewCard(cardResourceIds, PlayerCurrentScore, context)
    }

//    Box(modifier = Modifier.fillMaxSize()
//        .padding(top = 0.dp)
//        .wrapContentSize()
//        ,
//         contentAlignment = Alignment.Center
//    ) {
//        cardResourceIds.forEach { resourceId ->
//            val index = cardResourceIds.indexOf(resourceId)
//            Log.e("MainActivity", "要牌数量: ${cardResourceIds.size} index: $index")
//            Log.w("MainActivity", "资源名称: ${context.resources.getResourceEntryName(resourceId)}")
//            var offset = (index * 30).dp
//            Image(
//                painter = painterResource(id = resourceId),
//                contentDescription = "deal",
//                modifier = Modifier
//                    .size(100.dp)
//                    .offset(x = offset)
//                    .align(Alignment.Center)
//                    .padding(top = 0.dp)
//            )
//        }
//    }
    Box(modifier = Modifier.fillMaxSize()) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .align(Alignment.Center)
                .padding(top = 0.dp)
                .offset(y = 200.dp)
                .wrapContentSize(),

            horizontalArrangement = Arrangement.Absolute.Left, // 水平居左
            verticalAlignment = Alignment.CenterVertically // 垂直居中
        ) {
            Text(
                text = "闲家点数:${PlayerCurrentScore.value}", fontSize = 20.sp,
                fontWeight = FontWeight.Bold, fontStyle = FontStyle.Italic, color = Color.Blue
            )

            Box(modifier = Modifier.fillMaxSize()
                .padding(top = 20.dp).offset(x=-100.dp)
                .wrapContentSize()
                ,
                contentAlignment = Alignment.BottomStart
            ) {
                cardResourceIds.forEach { resourceId ->
                    val index = cardResourceIds.indexOf(resourceId)
                    Log.e("MainActivity", "要牌数量: ${cardResourceIds.size} index: $index")
                    Log.w("MainActivity", "资源名称: ${context.resources.getResourceEntryName(resourceId)}")
                    var offset = (index * 50).dp
                    Image(
                        painter = painterResource(id = resourceId),
                        contentDescription = "deal",
                        modifier = Modifier
                            .size(100.dp)
                            .offset(x = offset)
                            .align(Alignment.Center)
                            .padding(top = 0.dp)
                    )
                }
            }
        }
    }
}
